package com.jerei.plugin.init;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import ro.fortsoft.pf4j.PluginException;
import ro.fortsoft.pf4j.PluginWrapper;
import ro.fortsoft.pf4j.spring.SpringPlugin;

/**
 * Created by sunfeihu on 2016/11/21.
 */
public class InitPlugin extends SpringPlugin {

    public InitPlugin(PluginWrapper wrapper) {
        super(wrapper);
    }

    @Override
    public void start() throws PluginException {
        SchedulerFactoryBean sfb = this.getApplicationContext().getBean(SchedulerFactoryBean.class);
        if (!sfb.isRunning()) {
            sfb.start();
        }
    }

    @Override
    public void stop() {
        SchedulerFactoryBean sfb = this.getApplicationContext().getBean(SchedulerFactoryBean.class);
        sfb.stop();
    }

    @Override
    protected ApplicationContext createApplicationContext() {
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath*:application-" + this.getWrapper().getPluginId() + ".xml");
        applicationContext.setClassLoader(getWrapper().getPluginClassLoader());
        applicationContext.refresh();
        return applicationContext;
    }
}